package com.mingserve.report.controller;

import com.alibaba.fastjson2.JSON;
import com.mingserve.common.core.domain.R;
import com.mingserve.common.core.utils.DateUtils;
import com.mingserve.report.domain.AlarmDto;
import com.mingserve.report.service.AlarmService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

/**
 * 报警信息相关API
 *
 * @author lvwshuai
 * @date 2025-05-22
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/alarm")
public class AlarmController
{
    private final AlarmService alarmService;
    public void create() {
        String alarm = "{" +
                "            \"alarmContent\": \"根据设定阈值，设备运行在健康区域，其中测点1测点的acc_z方向振动强度最大\",\n" +
                "            \"alarmReason\": [\n" +
                "                \"时域：测点名称 测点1 通道 acc_z 健康区域 健康\",\n" +
                "                \"频域：测点名称 测点1 通道 acc_z 失效模式 定子失效\"\n" +
                "            ],\n" +
                "            \"alarmTime\": 1746609505859318,\n" +
                "            \"alarmType\": \"自适应阈值报警\",\n" +
                "            \"componentArea\": 2,\n" +
                "            \"componentCode\": \"stator\",\n" +
                "            \"componentType\": 3,\n" +
                "            \"deviceCode\": null,\n" +
                "            \"equipmentCode\": \"MINGLAB100040018ANMO00258NN\",\n" +
                "            \"pointCode\": \"MINGLAB100040018ANMO00250025ROLBESV\",\n" +
                "            \"pointTime\": 1746609505878740,\n" +
                "            \"repairSuggestion\": \"可较长时间运行\"\n" +
                "        }";
        AlarmDto alarmDto = JSON.parseObject(alarm, AlarmDto.class);
        alarmService.createReport(alarmDto);
    }

    /**
     * 检查报告是否存在
     */
    @GetMapping("check")
    public R<Boolean> check(@RequestParam("equipmentCode") String equipmentCode, @RequestParam("alarmTime") Long alarmTime)
    {
        if (equipmentCode == null || alarmTime == null) return R.fail("参数不正确");

        String fileName = equipmentCode + "_" + alarmTime + ".docx";
        String folder = "raw/alarm" + "/" + DateUtils.datePath(alarmTime);

        // 构建完整文件路径
        File file = new File(folder, fileName);

        return R.ok(file.exists());
    }

    /**
     * 生成报告
     */
    @PostMapping("/generate")
    public R generate(@RequestBody AlarmDto alarmDto)
    {
        alarmService.createReport(alarmDto);
        return R.ok();
    }

    /**
     * 删除报告
     */
    @PostMapping("/delete")
    public R<Boolean> delete(@RequestBody AlarmDto alarmDto)
    {
        String fileName = alarmDto.getEquipmentCode() + "_" + alarmDto.getAlarmTime() + ".docx";
        String folder = "raw/alarm" + "/" + DateUtils.datePath(alarmDto.getAlarmTime());

        // 构建完整文件路径
        File file = new File(folder, fileName);
        return R.ok(file.delete());
    }

    /**
     * 导出报告
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, AlarmDto alarmDto)
    {
        String fileName = alarmDto.getEquipmentCode() + "_" + alarmDto.getAlarmTime() + ".docx";
        String folder = "raw/alarm" + "/" + DateUtils.datePath(alarmDto.getAlarmTime());

        // 构建完整文件路径
        File file = new File(folder, fileName);
        try {
            // 设置响应头
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
            response.setContentLength((int) file.length());

            // 输出文件流
            Files.copy(file.toPath(), response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            throw new RuntimeException("文件下载失败", e);
        }
    }
}